package com.czy.owner.ui.workorder;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.OrderBespeakDetailsAdapter;
import com.czy.owner.adapter.OrderPackageDetailsAdapter;
import com.czy.owner.api.OrderCancleApi;
import com.czy.owner.api.OrderDetalisInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.WorkOrderDetailsModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.store.OnLineOrderActivity2;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.IntentUtils;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StringUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.widget.CountdownView;
import com.czy.owner.widget.MyRecyclerView;
import com.czy.owner.widget.UniversalDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by hedepu on 2017-09-06
 * 预约详情
 */

public class BesPeakDetailsActivity extends BaseActivity {
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.recyclerview_project)
    MyRecyclerView recyclerviewProject;
    @BindView(R.id.recyclerview_service)
    MyRecyclerView recyclerviewService;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.time_title)
    TextView timeTitle;
    @BindView(R.id.cv_seckill)
    CountdownView cvSeckill;
    //    @BindView(R.id.tv_bottom_type)
//    TextView tvBottomType;
//    @BindView(R.id.tv_order_money)
//    TextView tvOrderMoney;
    @BindView(R.id.btn_order_cancle)
    Button btnOrderCancle;
    @BindView(R.id.btn_order_confirm)
    Button btnOrderConfirm;
    @BindView(R.id.relat_bottom)
    RelativeLayout relatBottom;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.relat_time)
    RelativeLayout relatTime;
    @BindView(R.id.recyclerview_service_view)
    View recyclerviewServiceView;
    @BindView(R.id.recyclerview_project_view)
    View recyclerviewProjectView;
    @BindView(R.id.linear_cancle_people)
    LinearLayout linearCanclePeople;
    @BindView(R.id.tv_cancle_people)
    TextView tvCanclePeople;
    @BindView(R.id.tv_cancle_time)
    TextView tvCancleTime;
    @BindView(R.id.linear_cancle_time)
    LinearLayout linearCancleTime;
    @BindView(R.id.tv_order_deposit_money)
    TextView tvOrderDepositMoney;
    @BindView(R.id.relat_order_deposit)
    LinearLayout relatOrderDeposit;
    @BindView(R.id.tv_empty_content)
    TextView tvEmptyContent;
    @BindView(R.id.linear_empty)
    LinearLayout linearEmpty;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.tv_order_deposit_title)
    TextView tvOrderDepositTitle;

    @BindView(R.id.img_deposit)
    ImageView imgDeposit;
    @BindView(R.id.line_order_deposit)
    View lineOrderDeposit;

    private OrderBespeakDetailsAdapter orderBespeakDetailsAdapter;
    private OrderPackageDetailsAdapter orderPackageDetailsAdapter;
    public String CREATED = "created";
    public String WAITPAYDEPOSIT = "waitPayDeposit";
    public String WAITSERVICE = "waitService";
    public String INSERVICE = "inService";
    public String CANCELLED = "cancelled";

    WorkOrderDetailsModel workOrderModel;
    private String orderNumber;
    private String userOrderId;
    private String toastContent = "数据加载中...";
    private int storeId;
    private boolean isMessage;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_details_bespeak;
    }

    @Override
    protected void initInjector() {
        RxBus.getDefault().register(this);
        storeId = getIntent().getIntExtra("storeId", 0);
        orderNumber = getIntent().getStringExtra("orderNumber");
        userOrderId = getIntent().getStringExtra("userOrderId");
        isMessage = getIntent().getBooleanExtra("isMessage", false);
    }

    @Override
    protected void initViews() {
        toolbarTitle.setText("预约详情");
        imgRight.setImageResource(R.mipmap.order_phone);
        imgRight.setVisibility(View.GONE);
        tvEmptyContent.setText(toastContent);
        getData();

    }

    public void setTextData() {
        tvOrderNumber.setText("工单编号：" + workOrderModel.getOrderNumber());
        storeId = Integer.parseInt(workOrderModel.getStoreId());
        tvStoreName.setText(workOrderModel.getStoreName());
        //待处理
        if (workOrderModel.getOrderStatus().equals(CREATED)) {
            tvOrderStatus.setText("待处理");
            relatBottom.setVisibility(View.GONE);
            finish();
            //待付定金
        } else if (workOrderModel.getOrderStatus().equals(WAITPAYDEPOSIT)) {
            tvOrderStatus.setText("待付订金");
            cvSeckill.start(Long.parseLong(workOrderModel.getCreateTime()) + Integer.parseInt(OrderFragment.unPaidDepositTime) * 60 * 60 * 1000 - PhoneUtils.getTime());
            relatTime.setVisibility(View.VISIBLE);
//            tvOrderMoney.setText("¥" + DecimalUtil.formatNum(workOrderModel.getActualDepositAmount()));
            relatOrderDeposit.setVisibility(View.VISIBLE);
            tvOrderDepositTitle.setText("待付订金");
            tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderModel.getActualDepositAmount()));
            imgDeposit.setVisibility(View.GONE);
            //待服务
        } else if (workOrderModel.getOrderStatus().equals(WAITSERVICE)) {
            tvOrderStatus.setText("待服务");
            relatOrderDeposit.setVisibility(View.VISIBLE);
            if (Double.parseDouble(StringUtils.getString(workOrderModel.getDepositPayDetail().getPayedDepositAmount(), "0")) != 0) {

                imgDeposit.setVisibility(View.VISIBLE);
                tvOrderDepositMoney.setText("¥" + DecimalUtil.sub(workOrderModel.getDepositPayDetail().getPayedDepositAmount(), workOrderModel.getDepositPayDetail().getHang()));
            } else {
                tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderModel.getActualDepositAmount()));

            }
            tvOrderDepositTitle.setText("实付订金");

//            tvOrderMoney.setText("¥" + DecimalUtil.formatNum(workOrderModel.getActualDepositAmount()));
            btnOrderConfirm.setText("催单");
            btnOrderConfirm.setVisibility(View.GONE);
//            tvOrderMoney.setText("¥" + DecimalUtil.sub(workOrderModel.getDepositPayDetail().getPayedDepositAmount(), workOrderModel.getDepositPayDetail().getBalancePay()));

        } else if (workOrderModel.getOrderStatus().equals(CANCELLED)) {
            tvOrderStatus.setText("取消预约");
            relatBottom.setVisibility(View.GONE);
            btnOrderCancle.setVisibility(View.GONE);
            btnOrderConfirm.setVisibility(View.GONE);
            linearCanclePeople.setVisibility(View.VISIBLE);
            linearCancleTime.setVisibility(View.VISIBLE);
//            if (Double.parseDouble(StringUtils.getString(workOrderModel.getDepositPayDetail().getPayedDepositAmount(), "0")) != 0) {
//                relatOrderDeposit.setVisibility(View.VISIBLE);
//                imgDeposit.setVisibility(View.VISIBLE);
//                tvOrderDepositMoney.setText(DecimalUtil.sub(workOrderModel.getDepositPayDetail().getPayedDepositAmount(), workOrderModel.getDepositPayDetail().getHang()));
//            } else {
//                tvOrderDepositMoney.setText("¥" + DecimalUtil.formatNum(workOrderModel.getActualDepositAmount()));
//
//            }
            tvOrderDepositTitle.setText("退还订金");
            if ("store".equals(workOrderModel.getCancelType()))
                tvCanclePeople.setText("门店");
            else if ("owner".equals(workOrderModel.getCancelType()))
                tvCanclePeople.setText("本人");
            else if ("system".equals(workOrderModel.getCancelType()))
                tvCanclePeople.setText("超时系统自动取消");
            tvCancleTime.setText(TimeUtils.timeStamp2Date(workOrderModel.getCancelTime(), "yyyy年MM月dd日 HH:mm"));


        }
        if (workOrderModel.getPackageItemsList() != null && workOrderModel.getPackageItemsList().size() > 0) {
            recyclerviewService.setLayoutManager(new LinearLayoutManager(this));
            orderPackageDetailsAdapter = new OrderPackageDetailsAdapter(this, workOrderModel.getPackageItemsList());
            recyclerviewService.setAdapter(orderPackageDetailsAdapter);
            recyclerviewService.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
        } else {
            recyclerviewServiceView.setVisibility(View.GONE);
        }

        if (workOrderModel.getServiceItemsList() != null && workOrderModel.getServiceItemsList().size() > 0) {
            recyclerviewProject.setLayoutManager(new LinearLayoutManager(this));
            orderBespeakDetailsAdapter = new OrderBespeakDetailsAdapter(this, workOrderModel.getServiceItemsList());
            recyclerviewProject.setAdapter(orderBespeakDetailsAdapter);
            recyclerviewProject.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, R.drawable.shape_gray_divider_decoration));
        } else {
            recyclerviewProjectView.setVisibility(View.GONE);
        }
        tvTime.setText(workOrderModel.getConvertServiceTime());
        tvCarNum.setText(workOrderModel.getLicenseNumber() + " " + workOrderModel.getChName());
        tvContent.setText(StringUtils.getString(workOrderModel.getNote(), "无"));
        //金钱支付数目显示时，展示分割线
        lineOrderDeposit.setVisibility(relatOrderDeposit.getVisibility());


    }

    //获取订单
    private void getData() {
        OrderDetalisInfoApi orderDetalisInfoApi = new OrderDetalisInfoApi(new HttpOnNextListener<WorkOrderDetailsModel>() {
            @Override
            public void onNext(WorkOrderDetailsModel o) {
                workOrderModel = o;
                imgRight.setVisibility(View.VISIBLE);

                setTextData();
                linearEmpty.setVisibility(View.GONE);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                tvEmptyContent.setText("加载失败，点击重新加载...");
//                PhoneUtils.ShowToastMessage(BesPeakDetailsActivity.this, "获取订单信息异常");
            }
        }, this);
        ;
        orderDetalisInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        orderDetalisInfoApi.setOrderNumber(orderNumber);
        HttpManager.getInstance().doHttpDeal(orderDetalisInfoApi);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /*接受事件*/
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(CommonEvent changeText) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
          /*註銷*/
        RxBus.getDefault().unRegister(this);
    }

    //取消预约
    private void setCancle() {
        OrderCancleApi orderCancleApi = new OrderCancleApi(new HttpOnNextListener<Object>() {
            @Override
            public void onNext(Object o) {
                if (isMessage) {
                    startActivity(new Intent(BesPeakDetailsActivity.this, SubscribeOrdelActivity2.class).putExtra("currentId", 0));
                } else {
                    Intent intent = new Intent();
                    intent.setAction(SubscribeOrdelActivity.orderAction);
                    intent.putExtra("currentId", SubscribeOrdelActivity.currentId());
                    sendBroadcast(intent);
                }
                PhoneUtils.ShowToastMessage(BesPeakDetailsActivity.this, "取消预约成功");
                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                PhoneUtils.ShowToastMessage(BesPeakDetailsActivity.this, "取消预约失败");
            }
        }, this);
        ;
        orderCancleApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        orderCancleApi.setStoreId(storeId + "");
        orderCancleApi.setUserOrderId(userOrderId);
        HttpManager.getInstance().doHttpDeal(orderCancleApi);
    }

    @OnClick({R.id.btn_order_cancle, R.id.btn_order_confirm, R.id.linear_right_img, R.id.relat_order_deposit, R.id.linear_empty})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //取消预约
            case R.id.btn_order_cancle:
                if (workOrderModel.getOrderStatus().equals(WAITSERVICE) && Double.parseDouble(workOrderModel.getPayedDepositAmount()) != 0) {
                    //待服务
                    new UniversalDialog(this).builder()
                            .setCancelable(false)
                            .setMsg("取消预约，订金将全部原路退回，\n请及时查收~")
                            .setPositiveButton("我再想想", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                }
                            }).setNegativeButton("执意离去", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setCancle();

                        }
                    }).show();
                } else {
                    //待付款，和0元订金的
                    new UniversalDialog(this).builder()
                            .setCancelable(false)
                            .setMsg("确定取消预约？")
                            .setPositiveButton("我再想想", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                }
                            }).setNegativeButton("执意离去", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setCancle();

                        }
                    }).show();
                }
                break;
            case R.id.btn_order_confirm:
                if (workOrderModel.getOrderStatus().equals(WAITPAYDEPOSIT)) {
                    Intent ti = new Intent(BesPeakDetailsActivity.this, PaidSubscriptionActivity.class);
                    ti.putExtra("orderNumber", orderNumber);
                    ti.putExtra("userOrderId", userOrderId);
                    ti.putExtra("type", "3");
                    ti.putExtra("storeId", storeId);
                    startActivity(ti);
                }
                break;
            case R.id.linear_right_img:
                IntentUtils.onClickCallPhone(BesPeakDetailsActivity.this, workOrderModel.getServiceNumber());
                break;
            case R.id.relat_order_deposit:
                //箭头展示，则代表可以跳转详情
                if (imgDeposit.getVisibility() == View.VISIBLE) {
                    startActivity(new Intent(BesPeakDetailsActivity.this, PaymentDetailsActivity.class).putExtra("orderDetails", workOrderModel).putExtra("type", "2")
                            .putExtra("titleText", tvOrderDepositTitle.getText().toString()).putExtra("titleMoney", tvOrderDepositMoney.getText().toString()));
                }
                break;
            case R.id.linear_empty:
                if (tvEmptyContent.getText().toString().equals(toastContent))
                    return;
                tvEmptyContent.setText(toastContent);
                getData();
                break;

        }
    }


}
